package com.anxin.baseproject2.rx.progress;

import android.content.Context;
import android.widget.Toast;

import com.anxin.baseproject2.rx.RxObserver;

import io.reactivex.disposables.Disposable;


/**
 * Created by Huang、 on 2017/1/12.
 */
public abstract class ProgressObserver<T> extends RxObserver<T> implements ProgressCancelListener {
    private Context mContext;
    private ProgressDialogHandler mHandler;
    private Disposable disposable;

    public ProgressObserver(Context context){
        this(context,true);
    }

    public ProgressObserver(Context context, boolean cancel){
        this.mContext=context;
        mHandler=new ProgressDialogHandler(context,this,cancel);
    }

    private void showProgressDialog(){
        if (mHandler != null) {
            mHandler.obtainMessage(ProgressDialogHandler.SHOW_PROGRESS_DIALOG).sendToTarget();
        }
    }

    private void dismissProgressDialog(){
        if (mHandler != null) {
            mHandler.obtainMessage(ProgressDialogHandler.DISMISS_PROGRESS_DIALOG).sendToTarget();
            mHandler = null;
        }
    }


    /**
     * 订阅开始时调用
     * 显示ProgressDialog
     */

    @Override
    public void onSubscribe(Disposable d) {
        super.onSubscribe(d);
        showProgressDialog();
    }

    @Override
    public void onComplete() {
        dismissProgressDialog();
        Toast.makeText(mContext,"获取数据完成！",Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onError(Throwable e) {
        super.onError(e);
        dismissProgressDialog();
    }


    @Override
    public void onCancelProgress() {
        this.dispose();
    }
}
